<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>期刊论文管理</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <link href="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
    <!-- 引入DataTable CSS和JS -->
    <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" href="css/paper.css">
</head>
<body>
<img src="img/top.png" alt="生物工程学报" class="header-image">
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-custom">
    <div class="container d-flex justify-content-between align-items-center">
        <div class="d-flex">
            <a class="nav-link" href="index.html">首页</a>
            <a class="nav-link active" href="paper.html">论文管理</a>
        </div>
        <div class="d-flex">
            <a href="login.html" class="btn btn-outline-light smaller-btn">退出</a>
        </div>
    </div>
</nav>

<div class="container">
    <h4 class="mt-4 text-center">期刊论文管理</h4>
    <!-- 表格 -->
    <div class="table-responsive table-container mx-auto">
        <!-- 添加按钮 -->
        <div class="text-end mb-3">
            <button id="addButton" class="btn btn-success custom-left-align" data-bs-toggle="modal" data-bs-target="#paperModal">添加论文信息</button>
        </div>
        <!-- 表格主体-->
        <table id="dataTable" class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>ID</th>
                <th>标题</th>
                <th>作者引用</th>
                <th>摘要</th>
                <th>PDF URL</th>
                <th>发表日期</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- JS将在此插入行 -->
            </tbody>
        </table>
    </div>

    <!-- 添加/编辑模态框 -->
    <div class="modal fade" id="paperModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paperModalLabel">添加论文</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="paperForm">
                        <input type="hidden" id="paperId">
                        <div class="mb-3">
                            <label for="title" class="form-label">标题:</label>
                            <input type="text" class="form-control" id="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="author" class="form-label">作者引用:</label>
                            <input type="text" class="form-control" id="author" required>
                        </div>
                        <div class="mb-3">
                            <label for="abstract" class="form-label">摘要:</label>
                            <textarea class="form-control" id="abstract"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="pdfUrl" class="form-label">PDF URL:</label>
                            <input type="text" class="form-control" id="pdfUrl">
                        </div>
                        <div class="mb-3">
                            <label for="pubDate" class="form-label">发表日期:</label>
                            <input type="date" class="form-control" id="pubDate">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button id="submitPaper" type="button" class="btn btn-primary">提交</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 摘要详情模态框 -->
    <div class="modal fade" id="abstractModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">摘要详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <p id="fullAbstract"></p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 自定义脚本 -->
<script>
    $(document).ready(function() {
        var table = $('#dataTable').DataTable({
            "paging": true,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "lengthMenu": [5, 10, 25, 50, 100],
            "columnDefs": [
                {
                    "className": "dt-center",
                    "targets": "_all"
                },
                {
                    "targets": 3, // 摘要列索引为3
                    "render": function(data, type, row) {
                        if (type === 'display') {
                            let previewText = data.length > 25 ? data.substring(0, 25) + '...' : data;
                            return `
                                <span class="abstract-preview">${previewText}</span>
                                <span class="toggle-abstract" data-full-text="${data}">展开</span>
                            `;
                        }
                        return data;
                    }
                }
            ]
        });

        // 从服务器加载数据
        function loadData() {
            $.ajax({
                url: 'http://127.0.0.1:8080/paper/paperList',
                method: 'GET',
                success: function(data) {
                    $('#dataTable').DataTable().clear().draw(); // 清空现有数据
                    data.forEach(function(item) {
                        let pdfUrlLink = item.pdf_url ? `<a href="${item.pdf_url}" target="_blank">下载PDF</a>` : '无';
                        $('#dataTable').DataTable().row.add([
                            item.id,
                            item.title,
                            item.author,
                            item.abstracts,
                            pdfUrlLink,
                            item.pub_date,
                            `<button class="btn btn-primary edit-btn" data-id="${item.id}">编辑</button>
                             <button class="btn btn-danger delete-btn" data-id="${item.id}">删除</button>`
                        ]).draw(false);
                    });
                },
                error: function(error) {
                    console.error('加载数据时出错:', error);
                }
            });
        }

        // 初始化表格
        loadData();

        // 处理添加按钮点击以打开模态框
        $('#addButton').click(function() {
            $('#paperModalLabel').text('添加论文信息');
            $('#paperId').val('');
            $('#title').val('');
            $('#author').val('');
            $('#abstract').val('');
            $('#pdfUrl').val('');
            $('#pubDate').val('');
            $('#paperModal').modal('show');
        });

        // 提交表单以添加或编辑论文
        $('#submitPaper').click(function() {
            const paper = {
                id: $('#paperId').val(),
                title: $('#title').val(),
                author: $('#author').val(),
                abstracts: $('#abstract').val(),
                pdf_url: $('#pdfUrl').val(),
                pub_date: $('#pubDate').val()
            };

            let method = 'POST';
            let url = 'http://127.0.0.1:8080/paper/add';
            // 如果设置了ID，则为编辑操作
            if (paper.id) {
                method = 'PUT';
                url = 'http://127.0.0.1:8080/paper/edit';
            }

            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(paper),
                success: function(response) {
                    if (response === 'ok') {
                        $('#paperModal').modal('hide');
                        alert('论文' + (paper.id ? '更新':'添加') + '成功。');
                        loadData(); // 添加或更新后刷新表格
                    } else {
                        alert('失败：无法 ' + (paper.id ? '更新':'添加') + '论文。');
                    }
                },
                error: function(error) {
                    console.error('在' + (paper.id ? '更新':'添加') + '论文时出错:', error);
                }
            });
        });

        // 处理编辑操作
        $(document).on('click', '.edit-btn', function() {
            const paperId = $(this).data('id');

            $.ajax({
                url: `http://127.0.0.1:8080/paper/getPaperById?id=${paperId}`,
                method: 'GET',
                success: function(paper) {
                    $('#paperModalLabel').text('编辑论文');
                    $('#paperId').val(paper.id);
                    $('#title').val(paper.title);
                    $('#author').val(paper.author);
                    $('#abstract').val(paper.abstracts);
                    $('#pdfUrl').val(paper.pdf_url);
                    $('#pubDate').val(paper.pub_date);
                    $('#paperModal').modal('show');
                },
                error: function(error) {
                    console.error('获取论文时出错:', error);
                }
            });
        });

        // 处理删除操作
        $(document).on('click', '.delete-btn', function() {
            const paperId = $(this).data('id');
            if (confirm('确定要删除这篇论文吗？')) {
                $.ajax({
                    url: `http://127.0.0.1:8080/paper/delete/${paperId}`,
                    method: 'DELETE',
                    success: function(response) {
                        if (response === 'ok') {
                            alert('论文删除成功。');
                            loadData(); // 删除后刷新表格
                        } else {
                            alert('失败：无法删除论文。');
                        }
                    },
                    error: function(error) {
                        console.error('删除论文时出错:', error);
                    }
                });
            }
        });

        // 处理摘要展开/收起
        $(document).on('click', '.toggle-abstract', function(e) {
            e.preventDefault();
            let fullText = $(this).data('full-text');
            $('#fullAbstract').text(fullText); // 设置模态框内的文本
            $('#abstractModal').modal('show'); // 显示摘要详情模态框
        });

        // 关闭摘要详情模态框
        $('#abstractModal').on('hidden.bs.modal', function () {
            $('#fullAbstract').empty(); // 清除模态框内容
        });
    });
</script>
</body>
</html>